<template>
  <div class="user-profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <el-button link @click="$router.back()" style="margin-right: 10px;">返回</el-button>
          <h2>{{ isSelf ? '我的资料' : '用户资料' }}</h2>
        </div>
      </template>
      <el-descriptions :title="profile.username" :column="1" border>
        <el-descriptions-item label="邮箱">{{ profile.email }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ profile.firstname }} {{ profile.lastname }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ profile.phonenumber }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ profile.studentnumber }}</el-descriptions-item>
        <el-descriptions-item label="简介">{{ profile.aboutme }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 20px; text-align: right;">
        <el-button v-if="isSelf" type="primary" @click="goEdit">修改个人信息</el-button>
        <el-button v-else type="primary" @click="goPrivateMessage">私信</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { profileApi } from '@/utils/api'

export default {
  name: 'UserProfile',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const username = route.params.username
    console.log('前端请求用户名:', username)
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const isSelf = computed(() => user.username === username)
    const profile = ref({})

    const loadProfile = async () => {
      if (isSelf.value) {
        const res = await profileApi.get()
        profile.value = res.data
      } else {
        // 假设有API: /user/profile/{username}
        const res = await profileApi.getByUsername(username)
        profile.value = res.data
      }
    }

    const goEdit = () => {
      router.push('/profile')
    }
    const goPrivateMessage = () => {
      router.push({ path: '/private-message', query: { to: username } })
    }

    onMounted(() => {
      loadProfile()
    })

    // 监听路由参数变化，切换用户时重新加载资料
    watch(() => route.params.username, () => {
      loadProfile()
    })

    return {
      profile,
      isSelf,
      goEdit,
      goPrivateMessage
    }
  }
}
</script>

<style scoped>
.user-profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}
.profile-card {
  width: 600px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
</style> 